<template>
  <div class="question-create-container">
    <div class="page-header">
      <h2>{{ isEdit ? '编辑题目' : '创建题目' }}</h2>
      <el-button @click="goBack" plain round>
        <el-icon><ArrowLeft /></el-icon>
        返回题目列表
      </el-button>
    </div>

    <el-card class="create-form-card" shadow="hover">
      <el-form
        ref="questionFormRef"
        :model="questionForm"
        :rules="questionRules"
        label-position="top"
        status-icon
        :disabled="isReadonly"
      >
        <!-- 基本信息区域 -->
        <div class="form-section">
          <div class="section-title">
            <div class="title-icon">
              <el-icon><Document /></el-icon>
            </div>
            <h3>基本信息</h3>
          </div>

          <el-row :gutter="20">
            <el-col :xs="24" :sm="12">
              <el-form-item label="所属竞赛" prop="contestId">
                <el-select 
                  v-model="questionForm.contestId" 
                  placeholder="选择竞赛"
                  style="width: 100%"
                  :disabled="isEdit || contestId"
                >
                  <el-option 
                    v-for="contest in contestOptions" 
                    :key="contest.id" 
                    :label="contest.title" 
                    :value="contest.id"
                  />
                </el-select>
              </el-form-item>
            </el-col>
            <el-col :xs="24" :sm="12">
              <el-form-item label="题目类型" prop="typeId">
                <el-select 
                  v-model="questionForm.typeId" 
                  placeholder="选择题目类型"
                  style="width: 100%"
                  @change="handleTypeChange"
                >
                  <el-option 
                    v-for="type in questionTypes" 
                    :key="type.id" 
                    :label="type.typeName" 
                    :value="type.id"
                  />
                </el-select>
              </el-form-item>
            </el-col>
          </el-row>

          <el-row :gutter="20">
            <el-col :xs="24" :sm="12">
              <el-form-item label="题目排序" prop="orderNum">
                <template #label>
                  <div style="display: flex; align-items: center;">
                    题目排序
                    <el-tooltip
                      content="排序号决定题目在竞赛中的顺序，较小的数字排在前面"
                      placement="top"
                    >
                      <el-icon style="margin-left: 4px; color: #909399;"><InfoFilled /></el-icon>
                    </el-tooltip>
                  </div>
                </template>
                <el-input-number 
                  v-model="questionForm.orderNum" 
                  :min="1" 
                  :max="100" 
                  style="width: 100%"
                  placeholder="请输入题目序号"
                  controls-position="right"
                />
              </el-form-item>
            </el-col>
            <el-col :xs="24" :sm="12">
              <el-form-item label="难度" prop="difficulty">
                <el-select 
                  v-model="questionForm.difficulty" 
                  placeholder="选择难度"
                  style="width: 100%"
                >
                  <el-option label="简单" :value="1" />
                  <el-option label="中等" :value="2" />
                  <el-option label="困难" :value="3" />
                </el-select>
              </el-form-item>
            </el-col>
          </el-row>

          <el-row :gutter="20">
            <el-col :xs="24" :sm="12">
              <el-form-item label="分值" prop="score">
                <el-input-number 
                  v-model="questionForm.score" 
                  :min="1" 
                  :max="100" 
                  style="width: 100%"
                  controls-position="right"
                />
              </el-form-item>
            </el-col>
            <el-col :xs="24" :sm="12">
              <el-form-item label="答题时间限制(秒)" prop="timeLimit">
                <el-input-number 
                  v-model="questionForm.timeLimit" 
                  :min="10" 
                  :max="300" 
                  style="width: 100%"
                  controls-position="right"
                />
              </el-form-item>
            </el-col>
          </el-row>

          <el-form-item label="题目内容" prop="content">
            <el-input 
              v-model="questionForm.content" 
              type="textarea" 
              placeholder="请输入题目内容" 
              maxlength="2000" 
              show-word-limit
              rows="5"
            />
          </el-form-item>
        </div>

        <!-- 选项设置区域（针对选择题） -->
        <template v-if="isChoiceQuestion">
          <div class="choice-options-container">
            <div class="section-title">
              <div class="title-icon"><el-icon><Document /></el-icon></div>
              <h3>选项设置</h3>
            </div>
            
            <!-- 使用表格替代更稳定的布局方式 -->
            <el-table
              :data="questionForm.options"
              style="width: 100%;margin-bottom:20px;"
              :show-header="false"
              :row-style="{height: '60px'}"
              cell-class-name="option-cell"
            >
              <el-table-column width="60">
                <template #default="scope">
                  <div class="option-letter">{{scope.row.optionOrder}}</div>
                </template>
              </el-table-column>
              
              <el-table-column>
                <template #default="scope">
                  <el-input
                    v-model="scope.row.optionContent"
                    :placeholder="`请输入选项${scope.row.optionOrder}内容`"
                    :disabled="isReadonly"
                  />
                </template>
              </el-table-column>
              
              <el-table-column width="100">
                <template #default="scope">
                  <el-checkbox
                    v-model="scope.row.correct"
                    :disabled="isReadonly || (isSingleChoice && hasOtherCorrectOption(scope.$index))"
                    @change="() => handleOptionCorrectChange(scope.row, scope.$index)"
                  >
                    正确选项
                  </el-checkbox>
                </template>
              </el-table-column>
              
              <el-table-column v-if="!isReadonly" width="80">
                <template #default="scope">
                  <div class="option-actions">
                    <el-button 
                      type="danger" 
                      circle 
                      size="small" 
                      :icon="Delete" 
                      @click="removeOption(scope.$index)"
                      :disabled="questionForm.options.length <= 2"
                    />
                  </div>
                </template>
              </el-table-column>
            </el-table>
            
            <div v-if="!isReadonly" class="add-option-container">
              <el-button 
                type="primary" 
                plain 
                :disabled="questionForm.options.length >= 6"
                @click="addOption"
              >
                <el-icon><Plus /></el-icon> 添加选项
              </el-button>
            </div>
          </div>
        </template>

        <!-- 答案设置区域（针对判断题、填空题和简答题） -->
        <transition name="fade" mode="out-in">
          <div class="form-section" v-if="isJudgmentQuestion || isInputQuestion" key="answer-section">
            <div class="section-title">
              <div class="title-icon">
                <el-icon><Edit /></el-icon>
              </div>
              <h3>答案设置</h3>
            </div>

            <el-form-item v-if="isJudgmentQuestion" label="正确答案" prop="correctAnswer">
              <el-radio-group v-model="questionForm.correctAnswer">
                <el-radio :label="true">正确</el-radio>
                <el-radio :label="false">错误</el-radio>
              </el-radio-group>
            </el-form-item>

            <el-form-item v-if="isInputQuestion" label="参考答案" prop="referAnswer">
              <el-input 
                v-model="questionForm.referAnswer" 
                type="textarea" 
                placeholder="请输入参考答案" 
                rows="3"
              />
            </el-form-item>
          </div>
        </transition>

        <!-- 提交按钮区域 -->
        <div class="form-actions" v-if="!isReadonly">
          <el-button type="primary" round :loading="submitting" @click="submitForm">
            <el-icon><Check /></el-icon>
            {{ isEdit ? '保存修改' : '创建题目' }}
          </el-button>
          <el-button round @click="resetForm">
            <el-icon><Refresh /></el-icon>
            重置表单
          </el-button>
        </div>
        <div class="form-actions" v-else>
          <el-button @click="goBack" round>
            <el-icon><ArrowLeft /></el-icon>
            返回列表
          </el-button>
          <el-button type="primary" @click="editQuestion" round v-if="isEdit">
            <el-icon><Edit /></el-icon>
            编辑此题
          </el-button>
        </div>
      </el-form>
    </el-card>
  </div>
</template>

<script setup>
import { ref, reactive, computed, onMounted, nextTick, watch } from 'vue'
import { useRouter, useRoute } from 'vue-router'
import { ElMessage, ElMessageBox } from 'element-plus'
import { 
  ArrowLeft, 
  Document, 
  Edit, 
  Check, 
  Refresh, 
  Plus,
  Delete,
  InfoFilled
} from '@element-plus/icons-vue'
import { getQuestionDetail, createQuestion, updateQuestion, getQuestionTypes } from '@/api/question'
import { getContestList } from '@/api/contest'

const router = useRouter()
const route = useRoute()
const questionFormRef = ref(null)
const submitting = ref(false)
const questionId = ref(parseInt(route.params.id) || null)
const contestId = ref(parseInt(route.params.contestId) || null)
const isReadonly = ref(route.query.readonly === 'true')

// 判断是否是编辑模式
const isEdit = computed(() => {
  return !!questionId.value
})

// 竞赛和题目类型数据
const contestOptions = ref([])
const questionTypes = ref([])

// 题目表单数据
const questionForm = reactive({
  contestId: contestId.value || '',
  typeId: '',
  content: '',
  difficulty: 1,
  score: 10,
  timeLimit: 60,
  orderNum: 1,  // 设置默认值为1
  options: [
    { optionContent: '', optionOrder: 'A', correct: false },
    { optionContent: '', optionOrder: 'B', correct: false }
  ],
  correctAnswer: true,  // 用于判断题
  referAnswer: ''       // 用于填空题和简答题
})

// 表单验证规则
const questionRules = {
  contestId: [
    { required: true, message: '请选择所属竞赛', trigger: 'change' }
  ],
  typeId: [
    { required: true, message: '请选择题目类型', trigger: 'change' }
  ],
  content: [
    { required: true, message: '请输入题目内容', trigger: 'blur' },
    { min: 2, max: 2000, message: '内容长度应在2-2000个字符之间', trigger: 'blur' }
  ],
  difficulty: [
    { required: true, message: '请选择难度', trigger: 'change' }
  ],
  score: [
    { required: true, message: '请输入分值', trigger: 'blur' },
    { type: 'number', min: 1, max: 100, message: '分值应在1-100之间', trigger: 'blur' }
  ],
  timeLimit: [
    { required: true, message: '请输入答题时间限制', trigger: 'blur' },
    { type: 'number', min: 10, max: 300, message: '时间限制应在10-300秒之间', trigger: 'blur' }
  ],
  orderNum: [
    { required: true, message: '请输入题目排序号', trigger: 'blur' },
    { type: 'number', min: 1, max: 100, message: '排序号应在1-100之间', trigger: 'blur' }
  ],
  correctAnswer: [
    { required: true, message: '请选择正确答案', trigger: 'change' }
  ],
  referAnswer: [
    { required: true, message: '请输入参考答案', trigger: 'blur' }
  ]
}

// 判断是否是选择题
const isChoiceQuestion = computed(() => {
  return questionForm.typeId === 1 || questionForm.typeId === 2
})

// 判断是否是单选题
const isSingleChoice = computed(() => {
  return questionForm.typeId === 1
})

// 判断是否是判断题
const isJudgmentQuestion = computed(() => {
  return questionForm.typeId === 3
})

// 判断是否是填空题或简答题
const isInputQuestion = computed(() => {
  return questionForm.typeId === 4 || questionForm.typeId === 5
})

// 防抖函数
const debounce = (fn, delay) => {
  let timer = null
  return function(...args) {
    if (timer) clearTimeout(timer)
    timer = setTimeout(() => {
      fn.apply(this, args)
    }, delay)
  }
}

// 处理题目类型变更（使用防抖）
const handleTypeChange = debounce(() => {
  // 根据题目类型重置选项
  if (isChoiceQuestion.value) {
    if (questionForm.options.length < 2) {
      // 使用requestAnimationFrame来优化渲染
      requestAnimationFrame(() => {
        nextTick(() => {
          questionForm.options = [
            { optionContent: '', optionOrder: 'A', correct: false },
            { optionContent: '', optionOrder: 'B', correct: false }
          ]
        })
      })
    }
  } else {
    // 使用requestAnimationFrame来优化渲染
    requestAnimationFrame(() => {
      nextTick(() => {
        // 非选择题清空选项
        questionForm.options = []
      })
    })
  }
}, 200)

// 检查是否有其他正确答案（用于单选题）
const hasOtherCorrectOption = (currentIndex) => {
  if (!isSingleChoice.value) return false
  
  return questionForm.options.some((option, index) => {
    return index !== currentIndex && option.correct
  })
}

// 添加选项
const addOption = () => {
  if (questionForm.options.length >= 6) return // 最多6个选项
  
  const optionOrder = String.fromCharCode(65 + questionForm.options.length) // A, B, C, D, E, F
  
  // 使用requestAnimationFrame优化渲染性能
  requestAnimationFrame(() => {
    nextTick(() => {
      questionForm.options.push({
        optionContent: '',
        optionOrder,
        correct: false
      })
    })
  })
}

// 删除选项
const removeOption = (index) => {
  if (questionForm.options.length <= 2) return // 至少保留2个选项
  
  // 使用requestAnimationFrame优化渲染性能
  requestAnimationFrame(() => {
    nextTick(() => {
      questionForm.options.splice(index, 1)
      
      // 重新排序选项
      questionForm.options.forEach((option, idx) => {
        option.optionOrder = String.fromCharCode(65 + idx) // A, B, C, D, E, F
      })
    })
  })
}

// 获取题目类型列表
const fetchQuestionTypes = async () => {
  try {
    const res = await getQuestionTypes()
    questionTypes.value = res.data
  } catch (error) {
    console.error('获取题目类型失败', error)
    ElMessage.error('获取题目类型失败')
  }
}

// 获取竞赛列表
const fetchContestOptions = async () => {
  try {
    const res = await getContestList({
      page: 1,
      size: 100,
    })
    contestOptions.value = res.data.records
  } catch (error) {
    console.error('获取竞赛列表失败', error)
    ElMessage.error('获取竞赛列表失败')
  }
}

// 获取题目详情
const fetchQuestionDetail = async () => {
  if (!questionId.value) return
  
  try {
    const res = await getQuestionDetail(questionId.value)
    const questionData = res.data
    
    // 更新表单数据
    questionForm.contestId = questionData.contestId
    questionForm.typeId = questionData.typeId
    questionForm.content = questionData.content
    questionForm.difficulty = questionData.difficulty
    questionForm.score = questionData.score
    questionForm.timeLimit = questionData.timeLimit
    questionForm.orderNum = questionData.orderNum
    
    // 处理选项（针对选择题）
    if (questionData.options && questionData.options.length > 0) {
      questionForm.options = questionData.options.map(opt => ({
        optionContent: opt.optionContent,
        optionOrder: opt.optionOrder,
        correct: opt.correct
      }))
    }
    
    // 处理其他题型的答案
    if (questionData.typeId === 3) { // 判断题
      // 假设答案存储在某个字段中，这里需要根据实际情况调整
      questionForm.correctAnswer = questionData.correctAnswer === 'true'
    } else if (questionData.typeId === 4 || questionData.typeId === 5) { // 填空题或简答题
      // 假设参考答案存储在某个字段中，这里需要根据实际情况调整
      questionForm.referAnswer = questionData.referAnswer || ''
    }
  } catch (error) {
    console.error('获取题目详情失败', error)
    ElMessage.error('获取题目详情失败')
  }
}

// 提交表单
const submitForm = async () => {
  if (!questionFormRef.value) return
  
  await questionFormRef.value.validate(async (valid) => {
    if (valid) {
      // 构建提交数据
      const submitData = {
        contestId: questionForm.contestId,
        typeId: questionForm.typeId,
        content: questionForm.content,
        difficulty: questionForm.difficulty,
        score: questionForm.score,
        timeLimit: questionForm.timeLimit,
        orderNum: questionForm.orderNum
      }
      
      // 处理不同题型的答案
      if (isChoiceQuestion.value) {
        // 确保选择题至少有一个正确答案
        const hasCorrectOption = questionForm.options.some(opt => opt.correct)
        if (!hasCorrectOption) {
          ElMessage.warning('请至少选择一个正确答案')
          return
        }
        
        // 添加选项
        submitData.options = questionForm.options.map(opt => ({
          optionContent: opt.optionContent,
          optionOrder: opt.optionOrder,
          correct: opt.correct
        }))
      } else if (isJudgmentQuestion.value) {
        // 处理判断题答案
        submitData.correctAnswer = questionForm.correctAnswer
      } else if (isInputQuestion.value) {
        // 处理填空题或简答题参考答案
        submitData.referAnswer = questionForm.referAnswer
      }
      
      ElMessageBox.confirm(
        isEdit.value ? '确定要保存修改吗？' : '确定要创建此题目吗？',
        isEdit.value ? '保存确认' : '创建确认',
        {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'info'
        }
      ).then(async () => {
        submitting.value = true
        try {
          if (isEdit.value) {
            // 更新题目
            submitData.id = questionId.value
            await updateQuestion(questionId.value, submitData)
            ElMessage.success('更新题目成功')
          } else {
            // 创建题目
            await createQuestion(submitData)
            ElMessage.success('创建题目成功')
          }
          
          // 跳转到题目列表页
          setTimeout(() => {
            router.push('/contest/questions')
          }, 1500)
        } catch (error) {
          console.error(isEdit.value ? '更新题目失败' : '创建题目失败', error)
          ElMessage.error(isEdit.value ? '更新题目失败' : '创建题目失败')
        } finally {
          submitting.value = false
        }
      }).catch(() => {
        // 取消提交
      })
    } else {
      ElMessage.warning('请正确填写表单信息')
      return false
    }
  })
}

// 重置表单
const resetForm = () => {
  if (!questionFormRef.value) return
  
  ElMessageBox.confirm(
    '确定要重置表单吗？所有已填写的内容将被清空',
    '重置确认',
    {
      confirmButtonText: '确定重置',
      cancelButtonText: '取消',
      type: 'warning'
    }
  ).then(() => {
    questionFormRef.value.resetFields()
    // 重置选项
    if (isChoiceQuestion.value) {
      questionForm.options = [
        { optionContent: '', optionOrder: 'A', correct: false },
        { optionContent: '', optionOrder: 'B', correct: false }
      ]
    }
    ElMessage.success('表单已重置')
  }).catch(() => {
    // 取消重置
  })
}

// 返回题目列表
const goBack = () => {
  router.push('/contest/questions')
}

// 进入编辑模式
const editQuestion = () => {
  isReadonly.value = false
  router.replace(`/contest/question/edit/${questionId.value}`)
}

// 监听题目类型变化，更平滑地处理UI更新
watch(() => questionForm.typeId, (newVal, oldVal) => {
  if (newVal !== oldVal) {
    // 防止过快变更导致的ResizeObserver错误
    requestAnimationFrame(() => {
      handleTypeChange()
    })
  }
})

// 处理ResizeObserver错误的函数
const handleResizeObserverError = () => {
  window.addEventListener('error', (event) => {
    if (event.message && event.message.includes('ResizeObserver loop')) {
      event.stopImmediatePropagation();
      event.preventDefault();
      return false;
    }
  }, true);
}

// 处理选项正确性变更
const handleOptionCorrectChange = (option, index) => {
  if (isSingleChoice.value && option.correct) {
    // 如果是单选题且此选项被标记为正确，则其他选项标记为错误
    questionForm.options.forEach((opt, idx) => {
      if (idx !== index) {
        opt.correct = false
      }
    })
  }
}

onMounted(() => {
  // 获取竞赛数据和题目类型
  fetchContestOptions()
  fetchQuestionTypes()
  
  // 初始化ResizeObserver错误处理
  handleResizeObserverError()
  
  // 如果是编辑模式，获取题目详情
  if (isEdit.value) {
    fetchQuestionDetail()
  }
})
</script>

<style lang="scss" scoped>
.question-create-container {
  padding: 20px;
  
  /* 防止布局突然变化 */
  .el-form-item {
    contain: layout style; /* CSS containment 可减少重新计算布局 */
  }
  
  /* 使用固定高度避免 ResizeObserver 频繁触发 */
  :deep(.el-input__wrapper) {
    contain: layout style;
    min-height: 40px;
  }
  
  /* 防止过渡动画导致的 ResizeObserver 循环 */
  :deep(.el-table__body) {
    transform: translateZ(0); /* 强制硬件加速 */
    will-change: transform; /* 提前告知浏览器元素将变化 */
    contain: layout; /* 限制布局变化范围 */
  }
  
  /* 设置选项容器的固定高度，防止动态变化 */
  .choice-options-container {
    margin-bottom: 20px;
    contain: layout style; /* 限制布局和样式变化 */
  }
  
  /* 为排序字段的提示图标添加样式 */
  .order-num-tooltip {
    margin-left: 4px;
    font-size: 14px;
    color: #909399;
    cursor: pointer;
  }
  
  .page-header {
    display: flex;
    justify-content: space-between;
    align-items: center;
    margin-bottom: 20px;
    
    h2 {
      margin: 0;
      color: #303133;
      font-size: 24px;
      font-weight: 600;
    }
  }
  
  .create-form-card {
    border-radius: 12px;
    box-shadow: 0 4px 16px rgba(0, 0, 0, 0.05);
    overflow: hidden; /* 防止内容溢出引起的布局变化 */
    
    .form-section {
      margin-bottom: 30px;
      padding-bottom: 20px;
      border-bottom: 1px dashed #ebeef5;
      position: relative; /* 添加相对定位 */
      
      &:last-child {
        border-bottom: none;
        margin-bottom: 0;
      }
      
      .section-title {
        display: flex;
        align-items: center;
        margin-bottom: 20px;
        
        .title-icon {
          display: flex;
          justify-content: center;
          align-items: center;
          width: 36px;
          height: 36px;
          border-radius: 50%;
          background-color: #ecf5ff;
          color: #409eff;
          margin-right: 10px;
          font-size: 18px;
        }
        
        h3 {
          margin: 0;
          font-size: 18px;
          font-weight: 600;
          color: #303133;
        }
      }
    }
    
    .option-letter {
      font-weight: bold;
      text-align: center;
      font-size: 16px;
      color: #409EFF;
    }
    
    /* 优化表单和按钮样式 */
    :deep(.el-form-item) {
      margin-bottom: 22px; /* 固定表单项间距 */
    }
    
    .form-actions {
      display: flex;
      justify-content: center;
      gap: 20px;
      margin-top: 30px;
      
      .el-button {
        min-width: 120px;
        
        .el-icon {
          margin-right: 5px;
        }
      }
    }
  }
  
  .option-cell {
    padding: 8px;
  }
  
  .option-letter {
    font-weight: bold;
    text-align: center;
    font-size: 16px;
    color: #409EFF;
    width: 32px;
    height: 32px;
    line-height: 32px;
    border-radius: 50%;
    background-color: #ecf5ff;
    margin: 0 auto;
  }
  
  .add-option-container {
    margin-top: 10px;
    display: flex;
    justify-content: center;
  }
  
  .option-actions {
    display: flex;
    justify-content: center;
  }
}

@media screen and (max-width: 768px) {
  .question-create-container {
    .page-header {
      flex-direction: column;
      align-items: flex-start;
      gap: 10px;
    }
    
    .option-item {
      flex-direction: column;
      align-items: flex-start;
    }
  }
}

/* 添加过渡效果 */
.fade-enter-active,
.fade-leave-active {
  transition: opacity 0.3s ease, transform 0.3s ease;
}

.fade-enter-from,
.fade-leave-to {
  opacity: 0;
  transform: translateY(10px);
}
</style> 